<template>
  <div class="container mx-auto px-4 py-6">
    <!-- 页面标题 -->
    <div style="display: grid; justify-content: center; align-items: center;">
      <h1 class="text-2xl font-bold text-gray-800 mb-6">代课管理</h1>
    </div>

    <!-- 操作区域：新增 -->
    <div class="action-bar bg-white rounded-lg shadow-md p-4 mb-6 flex justify-end">
      <div class="search-container flex-1 flex">
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索名称..."
            class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        >
        <button
            @click="selectData"
            class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-r-md transition-colors"
        >
          <i class="fa fa-search mr-2">搜索</i>
        </button>
      </div>

      <button @click="openAddModal" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors flex items-center">
        <i class="fa fa-plus mr-2">新增代课</i>
      </button>
    </div>

    <!-- 表格 -->
    <div class="table-container w-full bg-white rounded-lg shadow-md overflow-hidden">
      <table class="family-table w-full">
        <thead>
        <tr class="bg-gray-50">
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程号</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程名称</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时长</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">教师ID</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生人数</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工资</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
        <tr v-for="(course,index) in courses" :key="course.courseId" class="hover-row hover:bg-gray-50 transition-colors">
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.courseId }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.courseName }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.duration }} 分钟</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.teacherId }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.studentCount }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ course.salary }}</td>

          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
            <button
                @click="openEditModal(index)"
                class="text-green-500 hover:text-green-700 transition-colors mr-3"
            >
              <i class="fa fa-pencil mr-1"></i>编辑
            </button>
            <button
                @click="deleteFamily(course.courseId)"
                class="text-red-500 hover:text-red-700 transition-colors mr-3"
            >
              <i class="fa fa-trash mr-1"></i>删除
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 空状态提示 -->
    <div v-if="courses.length === 0" class="empty-state w-full bg-white rounded-lg shadow-md p-8 text-center">
      <div class="empty-icon text-6xl text-gray-400 mb-4">
        <i class="fa fa-folder-open-o"></i>
      </div>
      <p class="text-gray-600 mb-4">暂无薪资数据</p>
      <button @click="openAddModal" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors">
        <i class="fa fa-plus mr-2"></i>添加薪资
      </button>
    </div>

    <!-- 查看、新增、编辑模态框 -->
    <div v-if="showViewModal || showAddModal || showEditModal" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="modal-content bg-white rounded-lg shadow-xl w-full max-w-4xl transform transition-all">
        <div class="modal-header flex justify-between items-center p-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            {{ showViewModal ? '查看薪资' : (showEditModal ? '编辑薪资' : '新增薪资') }}
          </h3>
          <button @click="closeModal" class="text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <div class="modal-body p-4">
          <!-- 家庭关系 -->
          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <h4 class="text-base font-medium text-gray-900 flex items-center">
                <span class="inline-block w-2 h-2 bg-purple-500 rounded-full mr-2"></span>
                课程关系
              </h4>
              <button
                  v-if="!showViewModal"
                  @click="addFamily"
                  class="text-sm text-purple-600 hover:text-purple-700 flex items-center"
              >
                <i class="fa fa-plus-circle mr-1"></i>添加关系
              </button>
            </div>

            <div class="course-form space-y-4">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <!-- 课程号 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">课程号</label>
                  <input
                      v-model="currentCourse.courseId"
                      type="text"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      required
                      :disabled="showViewModal"
                  >
                </div>

                  <!-- 代课教师选择 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">代课教师</label>
                  <select
                      v-model="currentCourse.teacherId"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      required
                      :disabled="showViewModal"
                  >
                    <option value="">请选择教师</option>
                    <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
                      {{ teacher.id }} - {{ teacher.name }}
                    </option>
                  </select>
                </div>

                  <!-- 课程名称 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">课程名称</label>
                  <input
                      type="text"
                      v-model="currentCourse.courseName"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                      required
                  >
                </div>

                <!-- 课程时长 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">课程时长(分钟)</label>
                  <input
                      type="number"
                      min="0"
                      v-model="currentCourse.duration"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                      required
                  >
                </div>

                <!-- 学生人数 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">学生人数</label>
                  <input
                      type="number"
                      min="0"
                      v-model="currentCourse.studentCount"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                      required
                  >
                </div>

                <!-- 代课工资 -->
                <div class="form-group">
                  <label class="block text-sm font-medium text-gray-700 mb-1">代课工资</label>
                  <input
                      type="number"
                      step="0.01"
                      min="0"
                      v-model="currentCourse.salary"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                      required
                  >
                </div>

                </div>
              </div>
            </div>
        </div>
        <div class="modal-footer flex justify-end p-4 border-t border-gray-200">
          <button @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors">
            关闭
          </button>
          <button
              v-if="showEditModal || showAddModal"
              @click="saveFamily"
              class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from "axios";
// 状态管理
const hasOpenFamily = ref(false)
const courses = ref([])

const showViewModal = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const currentCourse = ref({
  courseId: '',        // 课程号
  duration: 0,         // 课程时长（分钟）
  courseName: '',      // 课程名称
  teacherId: '',       // 代课教师ID
  studentCount: 0,     // 学生人数
  salary: 0.00         // 工资
})
const errors = ref({})
const teachers = ref([])


// 生命周期钩子：页面加载时获取初始数据
onMounted(() => {
  fetchInitialData()
})

const searchQuery = ref()

const selectData = async () =>{
  if (searchQuery.value.toString().trim() === "") return
  const famRes = await fetch(`/api/SubCourse/${searchQuery.value}`)
  const famData = await famRes.json()
  courses.value = famData.data || []
}

// 获取初始数据（部门、职务、职称、教师列表）
const fetchInitialData = async () => {
  try {
    const famRes = await fetch('/api/SubCourse')
    const famData  = await famRes.json()
    const response = await fetch('/api/teacher')
    const resData = await response.json()
    if (response.ok&&resData.code === 200) {
      teachers.value = resData.data
    }
    if (famRes.ok&&famData.code === 200) {
      courses.value = famData.data || []
    }
  } catch (error) {
    alert(`获取初始化数据失败：${error.message}`)
  }
}



// 添加新的家庭关系
const addFamily = async () => {
  if (hasOpenFamily.value === true) return
  currentCourse.value = {
    courseId: '',        // 课程号
    duration: 0,         // 课程时长（分钟）
    courseName: '',      // 课程名称
    teacherId: '',       // 代课教师ID
    studentCount: 0,     // 学生人数
    salary: 0.00         // 工资
  }
  hasOpenFamily.value = true

}


// 打开新增模态框
const openAddModal = () => {
  hasOpenFamily.value = true
  // 重置表单数据和错误
  currentCourse.value = {
    courseId: '',        // 课程号
    duration: 0,         // 课程时长（分钟）
    courseName: '',      // 课程名称
    teacherId: '',       // 代课教师ID
    studentCount: 0,     // 学生人数
    salary: 0.00         // 工资
  }
  errors.value = {}
  showAddModal.value = true
  showViewModal.value = false
  showEditModal.value = false
}

// 打开编辑模态框
const openEditModal = (index) => {
  hasOpenFamily.value = true
  showEditModal.value = true
  currentCourse.value = {
    courseId: '',        // 课程号
    duration: 0,         // 课程时长（分钟）
    courseName: '',      // 课程名称
    teacherId: '',       // 代课教师ID
    studentCount: 0,     // 学生人数
    salary: 0.00         // 工资
  }
  currentCourse.value.id = courses.value[index].id
  currentCourse.value.courseId = courses.value[index].courseId
  currentCourse.value.courseName = courses.value[index].courseName
  currentCourse.value.duration = courses.value[index].duration
  currentCourse.value.salary = courses.value[index].salary
  currentCourse.value.studentCount = courses.value[index].studentCount
}

// 关闭模态框
const closeModal = () => {
  hasOpenFamily.value = false
  showViewModal.value = false
  showAddModal.value = false
  showEditModal.value = false
  errors.value = {}
}

// 保存教师信息
const saveFamily = async () => {
  try {
    let response
    if (showAddModal.value) {
      // 新增
      response = await fetch('/api/SubCourse', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(currentCourse.value)
      })
    } else {
      response = await fetch(`/api/SubCourse`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(currentCourse.value)
      })
    }
    const data = await response.json()

    if (data.code === 200) {
      alert(showAddModal.value ? '教师成功' : '信息更新成功')
      closeModal()
      await fetchInitialData()
    } else {
      throw new Error(data.msg || (showAddModal.value ? '添加失败' : '更新失败'))
    }
  } catch (error) {
    alert(`操作失败: ${error.message}`)
  }finally {
    hasOpenFamily.value = false
  }
}

// 删除教师
const deleteFamily = (id) => {
  if (confirm('确定要删除吗？此操作不可撤销！')) {
    fetch(`/api/SubCourse/${id}`, {
      method: 'DELETE'
    })
        .then(response => response.json())
        .then(data => {
          if (data.code === 200) {
            alert('薪资删除成功')
            fetchInitialData() // 重新获取数据
          } else {
            throw new Error(data.msg || '删除失败')
          }
        })
        .catch(error => {
          alert(`删除失败: ${error.message}`)
        })
  }
}

</script>

<style scoped>
/* 导入Font Awesome */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

/* 基础样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
}

h1 {
  font-size: 24px;
  color: #333;
}


/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
.table-container {
  width: 100%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.family-table {
  width: 100%;
  border-collapse: collapse;
}

.family-table th, .family-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.family-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #555;
  text-transform: uppercase;
  font-size: 12px;
}

.family-table tr:last-child td {
  border-bottom: none;
}

.hover-row:hover {
  background-color: #f9f9f9;
  transition: background-color 0.2s ease;
}

/* 空状态样式 */
.empty-state {
  padding: 40px;
  text-align: center;
}

.empty-icon {
  color: #ccc;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  width: 100%;
  transform: scale(0.95);
  transition: transform 0.2s ease;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.modal-body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}

.modal-content:hover {
  transform: scale(1);
}

/* 表单样式 */
.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  line-height: 20px;
  color: #333;
  background-color: white;
  background-clip: padding-box;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
  border-color: #6366f1;
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

/* 按钮样式 */
button {
  cursor: pointer;
  border: none;
  background-color: transparent;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s ease;
}

button:hover {
  opacity: 0.9;
}

button:focus {
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

.bg-blue-500 {
  background-color: #3b82f6;
  color: white;
}

.bg-green-500 {
  background-color: #22c55e;
  color: white;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.text-green-500 {
  color: #22c55e;
}

.text-red-500 {
  color: #ef4444;
}

.text-purple-600 {
  color: #9333ea;
}

.px-4 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.rounded-md {
  border-radius: 0.375rem;
}

/* 错误提示样式 */
.text-red-500 {
  color: #ef4444;
}

.text-sm {
  font-size: 0.875rem;
}

.education-list > div, .family-list > div {
  position: relative;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
}


.text-xs {
  font-size: 0.75rem;
}

.font-medium {
  font-weight: 500;
}




.text-gray-800 {
  color: #1f2937;
}

.rounded-full {
  border-radius: 9999px;
}

/* 网格布局 */
.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}



.gap-4 {
  gap: 1rem;
}

/* 其他样式 */
.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.top-2 {
  top: 0.5rem;
}

.right-2 {
  right: 0.5rem;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.inline-block {
  display: inline-block;
}

.w-2 {
  width: 0.5rem;
}

.h-2 {
  height: 0.5rem;
}

.bg-blue-500 {
  background-color: #3b82f6;
}

.bg-green-500 {
  background-color: #22c55e;
}

.bg-purple-500 {
  background-color: #a855f7;
}

.rounded-full {
  border-radius: 9999px;
}

.mr-1 {
  margin-right: 0.25rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

.mr-3 {
  margin-right: 0.75rem;
}

.text-base {
  font-size: 1rem;
}

.font-medium {
  font-weight: 500;
}

.text-gray-900 {
  color: #111827;
}

.transition-colors {
  transition: color 0.2s ease, background-color 0.2s ease;
}
</style>

